package com.andy.spring.junit5.mockito.service.impl;

import com.andy.spring.junit5.mockito.User;
import com.andy.spring.junit5.mockito.repository.UserRepository;
import com.andy.spring.junit5.mockito.service.UserService;

public class DefaultUserService implements UserService {
    private UserRepository userRepository;

    public DefaultUserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User register(User user) {
        validate(user);
        User insertedUser = userRepository.insert(user);
        return insertedUser;
    }

    private void validate(User user) {
        if(user.getName() == null) {
            throw new RuntimeException("用户名称不能为空");
        }

        final boolean usernameAlreadyExists = userRepository.isUsernameAlreadyExists(user.getName());
        System.out.println("usernameAlreadyExists : " + usernameAlreadyExists);
        if(usernameAlreadyExists) {

            throw new RuntimeException("用户名称已存在");
        }
    }
}
